﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entities;
using System.Data.Common;

namespace BLL
{
	public class Generic
	{
		public static DbQuanLiTBDataContext DataContext;

		static Generic()
		{
			DataContext = new DbQuanLiTBDataContext("Data Source=liker-pc;Initial Catalog=QuanLyKhachSan;Integrated Security=True");
		}

		public static bool Insert<T>(T e)
			where T : class
		{
			DataContext.GetTable<T>().InsertOnSubmit(e);
			DataContext.SubmitChanges();
			return true;
		}

		public static IEnumerable<T> GetAll<T>()
			where T : class
		{
			return DataContext.GetTable<T>().ToList();
		}

		public static IEnumerable<T> FindByCondition<T>(Func<T, bool> func)
			where T : class
		{
			return DataContext.GetTable<T>()
					 .Where(func)
					 .ToList();
		}


		public static int DeleteByCondition<T>(Func<T, bool> func)
			where T : class
		{
			var ls = DataContext.GetTable<T>()
					 .Where(func)
					 .ToList();
			DataContext.GetTable<T>().DeleteAllOnSubmit(ls);
			var r = DataContext.GetChangeSet().Deletes.Count;
			DataContext.SubmitChanges();
			return r;
		}

		public static int EditByCondition<T>(Func<T, bool> func, Action<T> act)
			where T : class
		{
			DataContext.GetTable<T>()
								.Where(func)
								.ToList()
								.ForEach(act);
			int r = DataContext.GetChangeSet().Updates.Count;
			DataContext.SubmitChanges();
			return r;
		}

		public static void Commit()
		{
			DataContext.SubmitChanges();
		}

		public static bool TestConnection()
		{
			return DataContext.DatabaseExists();
		}

		public static void ReCreateteDBML(string s)
		{
			DataContext = new DbQuanLiTBDataContext(s);
		}

		public static DbConnection GetConnectionInfo()
		{
			return DataContext.Connection;
		}
	}
}
